import Request from "luch-request";

// 创建http实例
const http = new Request();

// const getBaseUrl = "http://23.224.198.161:5000";
// const getBaseUrl = "http://162.14.98.165/api-v1";
let apiUrl = ""

apiUrl = "http://127.0.0.1:5000/api-v1"


/* #ifdef MP-WEIXIN */
apiUrl = "https://www.unhejing.cn/api-v1"
/* #endif */
const getBaseUrl = apiUrl;

// 全局配置
http.setConfig((config) => {
  console.log("config: ", config);
  config.baseURL = getBaseUrl;
  config.timeout = 60000; // 默认值
  config.custom = {
    needAuth: false,
    showError: false,
  }; // 全局自定义参数默认值
  return config;
});

// request拦截器
http.interceptors.request.use(
  (config) => {
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
    // 初始化请求拦截器时，会执行此方法，此时data为undefined，赋予默认{}
    config.data = config.data || {};
    const token = uni.getStorageSync("token");
    if (token) {
      config.header.token = token;
    }
    return config;
  },
  (config) => {
    return Promise.reject(config);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const showError = response.config.custom.showError;
    const code = response.data.code || 200;
    uni.hideLoading();
    if (code === 200) {
      return response.data;
    } else if (code === 40001) {
      uni.showToast({
        title: "您还未登录或登录已过期,请重新登录",
        icon: "none",
      });
      uni.navigateTo({
        url: "/pages/login/login",
      });
      console.log("跳转");
    } else if (code === 500) {
      if (showError) {
        uni.showToast({
          title: "服务器错误，请稍后再试",
          icon: "none",
        });
        console.log(response);
      }
    } else {
      const msg = response.data.message;
      uni.showToast({
        title: msg,
        icon: "none",
      });
      return response.data;
    }
    return response.data;
  },
  (response) => {
	uni.hideLoading();
    const showError = response.config.custom.showError || "";
    // 不返回原始数据的情况下，服务器状态码不为200，modal弹框提示
    if (response.errMsg) {
      if (showError) {
        uni.showToast({
          title: "请求错误，请稍后再试",
          icon: "none",
        });
      }
    }
    return Promise.reject(response);
  }
);

export default http;
